#ifndef SERIALTHREAD_H
#define SERIALTHREAD_H

#include <memory>
#include <mutex>
#include <functional>
#include <QTimer>
#include <QObject>
#include <QSerialPort>

class SerialThread : public QObject
{
    Q_OBJECT
public:
    explicit SerialThread(QObject *parent = 0);
    ~SerialThread();

    void SetRun(bool flag);

    size_t GetRecvNum();
    size_t GetSndNum();
    void ClrRecvSndNum();

    bool IsOpen();

    void OpenSerial(const QString&);
    void CloseSerial();

signals:
    void SignalInfo(const QByteArray&);
    void SignalOpen(const QString&);
    void SignalSend(const QByteArray&);
    void SignalClose();

    void SignalCCID(const QString&);
    void SignalIMEI(const QString&);
    void SignalCSQ(const QString&);
    void SignalUpDown(bool);

public slots:
    void SlotRecvCircle();
    void SlotOpenSerailPort(const QString&);
    void SlotCloseSerialPort();
    void SlotSend(const QByteArray&);

private slots:
    void SlotTimer();
    void SlotRead();

private:
    void SendATCmd(const char* buf);
    bool OpenPort(const QString& name);  //new m_PortInfo
    void ClosePort();              //delete m_PortInfo

private:
    bool m_IsStart;
    bool m_IsRun;
    unsigned char m_NBState;

    //size_t recvNum;
    //size_t sndNum;
    std::atomic_int recvNum;
    std::atomic_int sndNum;

    QTimer* m_Timer;
    QThread* m_Thread;

    QByteArray m_SendQStr;

    std::mutex m_Mutex;
    std::mutex m_NumMutex;

private:
    QSerialPort* m_Port;
    QSerialPortInfo* m_PortInfo;
    bool m_IsOpen;

    std::mutex m_SerialMutex;
};

#endif // SERIALTHREAD_H
